import { useState } from 'react'

function App() {
  const [oldImg, setoldImg] = useState('')
  const [img, setImg] = useState('')
  const imgCompressFn = (imgBase64, quality, mimeType) => {
    let canvas = document.createElement('canvas')
    let img = document.createElement('img')
    img.src = imgBase64
    img.onload = () => {
      canvas.width = canvas.height = 300;
      let ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
      let newImgBase = canvas.toDataURL(mimeType, quality / 100)
      setImg(newImgBase)
      console.log(newImgBase, '压缩后的');
    }
  }
  const handleChange = (event) => {
    const file = event.target.files[0];
    const readObj = new FileReader()
    
    readObj.onload = () => {
      console.log(readObj.result, '压缩前的');
      imgCompressFn(readObj.result, 50, 'image/jpeg');
      setoldImg(readObj.result)
    }
    readObj.readAsDataURL(file)
  };
  return (
    <>
      <h3>图片压缩</h3>
      <div>
        <input type="file" onChange={handleChange} />
      </div>
      <h2>原图片</h2>
      <img style={{ width: 300, height: 300, backgroundColor: "green" }} src={oldImg} alt="" />
      <h2>压缩后的图片</h2>
      <img style={{ width: 300, height: 300, backgroundColor: "red" }} src={img} alt="" />
    </>
  )
}
export default App


